package cn.jason.ymcc.service.impl;

import cn.jason.ymcc.domain.Course;
import cn.jason.ymcc.domain.CourseMarket;
import cn.jason.ymcc.domain.CourseOrder;
import cn.jason.ymcc.domain.CourseOrderItem;
import cn.jason.ymcc.dto.CourseOrderCreateParamsDto;
import cn.jason.ymcc.dto.PayDto;
import cn.jason.ymcc.exception.GlobalException;
import cn.jason.ymcc.feign.CourseUserLearnFeignClient;
import cn.jason.ymcc.mapper.CourseOrderMapper;
import cn.jason.ymcc.result.JSONResult;
import cn.jason.ymcc.service.ICourseOrderItemService;
import cn.jason.ymcc.service.ICourseOrderService;
import cn.jason.ymcc.util.AssertUtil;
import cn.jason.ymcc.util.CodeGenerateUtils;
import cn.jason.ymcc.vo.CourseItemVo;
import cn.jason.ymcc.vo.CourseOrderVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jason
 * @since 2022-07-29
 */
@Service
@Slf4j
public class CourseOrderServiceImpl extends ServiceImpl<CourseOrderMapper, CourseOrder> implements ICourseOrderService {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private CourseUserLearnFeignClient courseInfoForOrderFeignClient;
    @Autowired
    private ICourseOrderItemService courseOrderItemService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    @Transactional
    public String placeOrder(CourseOrderCreateParamsDto dto) {
        //检查token是否有效
        Long loginId = 1L;
        String courseIdsStr = StringUtils.join(dto.getCourseIds(), ",");
        String key = courseIdsStr + ":" + loginId;
        Object tokenTT = redisTemplate.opsForValue().get(key);
        AssertUtil.isNotNull(tokenTT, "token失效，请重新下单！");
        AssertUtil.isEquals(dto.getToken(), tokenTT.toString(), "token错误，请重新下单");
        //业务校验
        JSONResult jsonResult = courseInfoForOrderFeignClient.courseOrderInfo(courseIdsStr);
        AssertUtil.isTrue(jsonResult.isSuccess(), "信息错误，下单失败！");
        AssertUtil.isNotNull(jsonResult.getData(), "服务不可达，下单失败！");
        String objStr = JSON.toJSONString(jsonResult.getData());
        CourseOrderVo orderVo = JSONObject.parseObject(objStr, CourseOrderVo.class);
        List<CourseItemVo> courseInfos = orderVo.getCourseInfos();
        AssertUtil.isNotNull(courseInfos, "课程信息有误，下单失败");
        //保存订单
        //保存主订单
        Date date = new Date();
        CourseOrder order = new CourseOrder();
        order.setCreateTime(date);
        order.setOrderNo(CodeGenerateUtils.generateOrderSn(loginId));
        order.setStatusOrder(0);
        order.setUserId(loginId);
        order.setVersion(0);
        order.setPayType(dto.getPayType());
        //保存子订单 统计出总金额
        StringBuilder sb = new StringBuilder();
        sb.append("课程【");
        courseInfos.forEach(courseInfoVo -> {
            Course course = courseInfoVo.getCourse();
            CourseMarket courseMarket = courseInfoVo.getCourseMarket();
            CourseOrderItem item = new CourseOrderItem();
            item.setAmount(courseMarket.getPrice());
            item.setCount(1);
            order.setTotalCount(order.getTotalCount() + 1);
            order.setTotalAmount(order.getTotalAmount().add(item.getAmount()));
            sb.append(course.getName()).append(",");
            item.setCreateTime(date);
            item.setCourseId(course.getId());
            item.setCourseName(course.getName());
            item.setCoursePic(course.getPic());
            item.setVersion(order.getVersion());
            item.setOrderNo(order.getOrderNo());
            //子订单放入order中
            order.getItems().add(item);
        });
        sb.append("】订单");
        //修改主订单
        order.setTitle(sb.toString());
        //将保存主订单和子订单交给MQ的事务监听器，再传过去
        HashMap<Object, Object> extParam = new HashMap<>();
        extParam.put("userId", loginId);
        extParam.put("courseId", courseIdsStr);
        PayDto payDto = new PayDto(
                order.getTotalAmount(),
                order.getPayType(),
                null,
                order.getOrderNo(),
                order.getUserId(),
                JSON.toJSONString(extParam),
                order.getTitle()
        );
        log.info("发送事务消息");
        //创建消息体
        Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(payDto)).build();
        TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(
                "service-order-producer",
                "course-order-topic:course-order-tag",
                //消息体
                message,
                //额外参数
                order
        );
        log.info("发送完事务消息--检查事务消息状态");
        LocalTransactionState localTransactionState = transactionSendResult.getLocalTransactionState();
        SendStatus sendStatus = transactionSendResult.getSendStatus();
        if (localTransactionState != LocalTransactionState.COMMIT_MESSAGE || sendStatus != SendStatus.SEND_OK) {
            log.info("发送信息状态异常");
            throw new GlobalException("下单失败了大莽！！");
        }
        //删除防重复token
        redisTemplate.delete(key);
        return order.getOrderNo();
    }

    /**
     * 保存主订单和子订单
     *
     * @param courseOrder
     */
    @Override
    public void saveOrderAndItems(CourseOrder courseOrder) {
        CourseOrder orderTmp = selectOrderByOrderNo(courseOrder.getOrderNo());
        AssertUtil.isNull(orderTmp, "订单已经存在，下单失败");
        //保存主订单
        insert(courseOrder);
        courseOrder.getItems().forEach(item -> {
            item.setOrderId(courseOrder.getId());
            //保存子订单
            courseOrderItemService.insert(item);
        });
    }

    /**
     * 根据订单号查询订单
     *
     * @param orderNo
     * @return
     */
    @Override
    public CourseOrder selectOrderByOrderNo(String orderNo) {
        Wrapper<CourseOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no", orderNo);
        return selectOne(wrapper);
    }

    @Override
    public void cancelOrder(String orderNo) {
        CourseOrder courseOrder = selectOrderByOrderNo(orderNo);
        AssertUtil.isNotNull(courseOrder, "订单不存在");
        if (courseOrder.getStatusOrder().intValue() != CourseOrder.STATE_PAY_SUCCESS.intValue()) {
            courseOrder.setStatusOrder(CourseOrder.STATE_CANCEL);
            updateById(courseOrder);
        }
    }
}
